﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
using System.Windows.Forms;

namespace FennecUI
{
    public class AppletCommunicationBus
    {
        public AppletCommunicationBus()
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _socket.Bind(new IPEndPoint(IPAddress.Loopback,4422));
            _socket.BeginReceive(_data,0,1024,SocketFlags.None,onReceiveData,new object());
        }

        private void onReceiveData(IAsyncResult ar)
        {
            int read=_socket.EndReceive(ar);
            if (read > 0)
            {
                processCommand(ASCIIEncoding.ASCII.GetString(_data,0,read));
                _socket.BeginReceive(_data, 0, 1024, SocketFlags.None, onReceiveData, new object());
            }
        }

        private void processCommand(string command)
        {
            Guid senderGuid=Guid.Parse(command.Substring(0,38));
            byte instance=Convert.ToByte(command.Substring(38, 2),16);
            MessageType messageType = (MessageType)(Convert.ToByte(command.Substring(40, 2),16));
            String message = command.Substring(command.IndexOf("+") + 1);

            onCommandReceived(senderGuid, instance, messageType, message);
        }

        private Socket _socket;
        private byte[] _data = new byte[1024];

        public delegate void CommandReceived(Guid senderGuid,byte senderInstance, MessageType messageType,string message);
        public event CommandReceived onCommandReceived;
    }

    public enum MessageType:byte{
        OpenApplet=0x00,
        OpenAppletAdvanced=0x01,
        OpenFile=0x02,
        EnterFullMode=0x03
    }
}
